package eva.savant.core.navigation

import eva.savant.businessobject.ad.Menu
import eva.savant.businessobject.ad.Rol

import javax.faces.bean.ManagedBean
import javax.faces.bean.SessionScoped

@ManagedBean
@SessionScoped
public class Builder implements Serializable {

  def navigation = new Navigation()

  private static String getBean(String url){

    def ind1= url.lastIndexOf('/')

    def ind2= url.lastIndexOf('.')

    return ind1 > 0 && ind2 > 0? url.substring(ind1 + 1, ind2) : null
  }

  public void buildMenuTree(List<Rol> lsRol){

    def roles = new ArrayList<Node>()

    for (rol in lsRol) {

      def menu = rol.menu

      def node = buildNode(menu)

      roles.add(node)

      buildChildMenus(menu,node)

    }

    navigation.node= roles

    navigation.defaultNode= roles.get(0)
  }

  private void buildChildMenus(Menu parentMenu, Node parentNode) {

    for (menu in parentMenu.lsMenu) {

    def node = buildNode(menu)

    parentNode.node.add(node)

    if(menu?.lsMenu?.size()>0)

    buildChildMenus(menu,node) }

  }

  private static Node buildNode(Menu menu) {

    def transaccion= menu.transaccion

    def node= new Node()

    node.id= menu.id

    node.label= menu.nombre


    if(menu?.lsMenu?.size() < 1 && menu.transaccion != null) {

      def content= new Content()

      content.id= transaccion.id

      content.code= transaccion.codigo

      content.bean= getBean(transaccion.ruta)

      content.title= transaccion.nombre

      content.pageRef= transaccion.ruta

      node.leaf= true

      node.link= true

      node.content= content
    }

    return node
  }

  public Node getNode(String nodeId) {

    return nodeSearch(navigation.node, nodeId)
  }

  private Node nodeSearch(List<Node> nodes, String nodeId) {

    for (node in nodes) {

      if(node.id.equals(nodeId)) return node

      if(node.node != null && nodes.size() > 0) {

      def foundNode = nodeSearch(node.node, nodeId)

      if(foundNode != null) return foundNode }

    }

    return null
  }

  public Node getContent(String contentId) {

    return contentSearch(navigation.node, contentId)
  }

  private Node contentSearch(List<Node> nodes, String contentId) {

    for (node in nodes) {

      if(node.content != null && node.content.id.equals(contentId)) return node

      if(node.content != null && node.content.code.equals(contentId)) return node

      if(node.node != null && nodes.size() > 0) {

      def foundNode = contentSearch(node.node, contentId)

      if(foundNode != null) return foundNode }

    }

    return null
  }

}
